<template>
	<div>
		<div style="padding-top: 1.125vw">
			<!-- 实时粒度 -->
			<div class="tag-group" v-if="granularityCurrent === 0">
				<div class="tag-label">分析日期</div>
				<div class="today">
					<div>{{ today }}</div>
					<div class="refresh" @click="realRefresh">5分钟自动刷新</div>
				</div>
			</div>
			<div v-if="[1, 2, 3].includes(granularityCurrent)">
				<div class="tag-group">
					<div class="tag-label">分析日期</div>
					<div class="date">
						<div v-if="granularityCurrent == 1">
							<el-date-picker v-model="sameDay.time" type="date" placeholder="请选择" />
						</div>
						<div v-if="granularityCurrent == 2">
							<el-date-picker v-model="sameDay.week" type="week" format="[Week] ww" placeholder="请选择周"
								:disabled-date="disabledWeek" />
						</div>
						<div v-if="granularityCurrent == 3"><el-date-picker v-model="sameDay.month" type="month"
								placeholder="请选择月" /></div>
					</div>
				</div>
				<div class="tag-group" v-if="granularityCurrent == 2 || granularityCurrent == 3">
					<div class="tag-label">日期类型</div>
					<div class="date">
						<div>
							<el-select v-model="sameDay.weekType" placeholder="请选择">
								<el-option v-for="(item, index) in weekOptions" :key="index" :label="item.label"
									:value="item.value" />
							</el-select>
						</div>
					</div>
				</div>
				<div class="tag-group">
					<div class="tag-label">分析时段</div>
					<div class="date">
						<el-select v-model="sameDay.period" placeholder="请选择">
							<el-option v-for="(item, index) in periodOptions" :key="index" :label="item.label"
								:value="item.value" />
						</el-select>
					</div>
				</div>
			</div>
			<!-- 自定义日期 -->
			<!-- <div v-if="granularityCurrent == 4">
        <div class="tag-group">
          <div class="tag-label">分析日期</div>
          <div class="date">
            <el-date-picker
              v-model="sameDay.time"
              type="daterange"
              range-separator="至"
              value-format="YYYY-MM-DD"
              format="YYYY-MM-DD"
              start-placeholder="选择开始日期"
              end-placeholder="选择结束日期"
              @change="changeTable"
            />
          </div>
        </div>
        <div class="tag-group">
          <div class="tag-label">分析时段</div>
          <div class="date">
            <el-select
              style="width: 100%;"
              v-model="sameDay.period"
              placeholder="请选择"
              @change="changeTable"
            >
              <el-option
                v-for="(item, index) in periodOptions"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
        </div>
      </div> -->
			<!-- 搜索 -->
			<div class="search">
				<div class="search-input"><el-input v-model="sameDay.keywork" placeholder="请输入" :prefix-icon="Search"
						@keyup.enter.native="getList" /></div>
				<!-- <div class="export">
          <span>导出Excel</span>
        </div> -->
			</div>
			<!-- 表格 -->
			<div class="table" v-if="tableData && tableData.length"
				style="max-height: 58vh; overflow-y: auto; display: block">
				<el-table :data="tableData" style="width: 100%" highlight-current-row @current-change="currentChange"
					v-loading="tableLoading">
					<!-- <el-table-column prop="rank" label="排行" width="100"> -->
					<!-- <template #default="{ $index }">
              <div class="index-color">{{ $index + 1 }}</div>
            </template>
          </el-table-column> -->
					<el-table-column :prop="`roadName`" label="道路组名称" v-if="switchCurrent === 0">
						<template #default="{ row }">
							<div>
								{{ row.roadName }} {{ row.direction || "" }}
							</div>
						</template>
					</el-table-column>
					<el-table-column prop="railway" label="拥堵路段" v-if="switchCurrent === 1" />
					<!-- <el-table-column prop="num" label="拥堵指数" width="100">
            <template #default="{ row }">
              <span
                class="congestion-num"
                :class="{ red: row.num > 2, orange: row.num > 1.5 && row.num < 2 }"
                >{{ row.num }}</span
              >
            </template>
          </el-table-column> -->
				</el-table>
				<el-pagination class="mt-10 pagination-sty" @current-change="changePage" :current-page="pageNum"
					:page-size="pageSize" background layout="prev, pager, next" :total="frontTableData.length"
					hide-on-single-page />
			</div>
			<div class="not-data" v-else> 暂无数据 </div>
		</div>
	</div>
</template>
<script>
	import {
		defineComponent,
		inject,
		reactive,
		toRefs,
		onMounted,
		nextTick,
		computed,
		onBeforeUnmount,
		emits,
	} from 'vue';
	import {
		useMapStore
	} from '@/store/modules/map';
	import customDatePicker from '@/components/customDatePicker';
	import {
		Search
	} from '@element-plus/icons-vue';
	import {
		selectYdRoadRecord,
		selectYdRoadRecord2
	} from '@/api/tomae';
	import {
		getCustomRoadSelectList
	} from '@/api/tomae';
	import dayjs from 'dayjs';
	export default defineComponent({
		components: {
			customDatePicker
		},
		props: {
			is_ctdd_show: false,
		},
		emits: ['tags-click', 'tableSelect'],
		setup(props, {
			emit
		}) {
			const mapStore = useMapStore();

			const state = reactive({
				map: computed(() => mapStore.ownMap),
				datePicker: null,
				switchCurrent: 0,
				pageNum: 1,
				pageSize: 8,
				frontTableData: [],
				periodRange: '',
				granularityList: [{
						label: '实时',
					},
					{
						label: '日',
					},
					{
						label: '周',
					},
					{
						label: '月',
					},
					{
						label: '自定义时间',
					},
				],
				granularityCurrent: 4,
				today: '',
				sameDay: {
					time: '',
					week: '',
					month: '',
					period: 1,
					weekType: 1,
					keywork: '',
				},
				weekOptions: [{
						label: '全部日期',
						value: 1,
					},
					{
						label: '工作日',
						value: 2,
					},
					{
						label: '节假日',
						value: 3,
					},
				],
				periodOptions: [{
						label: '整天(00:00 ~ 24:00)',
						value: 0,
					},
					{
						label: '全天(06:00 ~ 22:00)',
						value: 1,
					},
					{
						label: '早平峰(06:00 ~ 07:00)',
						value: 2,
					},
					{
						label: '早高峰(07:00 ~ 09:00)',
						value: 3,
					},
					{
						label: '上午平峰(09:00 ~ 11:00)',
						value: 4,
					},
					{
						label: '午高峰(11:00 ~ 13:00)',
						value: 5,
					},
					{
						label: '下午平峰(13:00 ~ 17:00)',
						value: 6,
					},
					{
						label: '晚高峰(17:00 ~ 19:00)',
						value: 7,
					},
				],
				timer: null,
				currentRow: '',
				tableData: [],
				tableLoading: false,
				polylineList: [],
				startPoint: '',
				endPoint: '',
				viaPoint: [],
			});
			// 获取当前时间
			const getToday = (add) => {
				var date = new Date();
				if (add) {
					date = new Date(date.getTime() + 1000 * 60 * 60 * 24 * add);
				}
				var year = date.getFullYear();
				var dateArr = [
					date.getMonth() + 1,
					date.getDate(),
					date.getHours(),
					date.getMinutes(),
					date.getSeconds(),
				];
				for (var i = 0; i < dateArr.length; i++) {
					if (dateArr[i] >= 1 && dateArr[i] <= 9) {
						dateArr[i] = '0' + dateArr[i];
					}
				}
				var strDate =
					year +
					'-' +
					dateArr[0] +
					'-' +
					dateArr[1] +
					' ' +
					dateArr[2] +
					':' +
					dateArr[3] +
					':' +
					dateArr[4];
				state.today = strDate;
				return state.today;
			};
			state.sameDay.time = [getToday(-1), getToday()];
			// 粒度点击
			const granularityClick = (index) => {
				state.granularityCurrent = index;
				if (index == 0) {
					getToday();
					state.timer = setTimeout(() => {
						realRefresh();
					}, 1000 * 60 * 5);
				} else {
					clearTimeout(state.timer);
				}
			};
			// 刷新
			const realRefresh = () => {
				getToday();
				clearTimeout(state.timer);
				state.timer = setTimeout(() => {
					realRefresh();
				}, 1000 * 60 * 5);
			};
			//禁止周
			const disabledWeek = (date) => {
				console.log(date);
			};
			// 表格选择
			const currentChange = async (currentRow, oldCurrentRow) => {

				if (!currentRow) {
					return;
				}
				state.map.clearOverlays();
				state.startPoint = '';
				state.endPoint = '';
				state.currentRow = currentRow;
				console.log(state)
				if (currentRow.origin) {
					state.startPoint = new window.BMap.Point(
						currentRow.origin.split(',')[0],
						currentRow.origin.split(',')[1],
					);
					if (state.map.getZoom() < 16) {
						state.map.setZoom(16);
					}
					state.map.panTo(state.startPoint);
				}
				if (currentRow.terminus) {
					state.endPoint = new window.BMap.Point(
						currentRow.terminus.split(',')[0],
						currentRow.terminus.split(',')[1],
					);
				}

				// 不知道这里为什么是这个逻辑，如果点击到这种数据的道路，再点击到其他道路，会画出来两次道路，且数据不正确
				// if (currentRow.customRoadMiddleList) {
				//   state.viaPoint = [];
				//   currentRow.customRoadMiddleList.forEach((item) => {
				//     let p = new window.BMap.Point(item.middle.split(',')[0], item.middle.split(',')[1]);
				//     state.viaPoint.push(p);
				//   });
				// }
				console.log(state, 'state')
				if (state.startPoint && state.endPoint) {
					let ddd = [
						dayjs().endOf('day').subtract(1, 'day').format('YYYY-MM-DD'),
						dayjs().endOf('day').format('YYYY-MM-DD'),
					];
					let params = {
						dateTime: ddd[0],
						compareDateTime: ddd[1],
						type: 2,
						roadId: currentRow.roadId
					}

					console.log("params", params);
					const data = await selectYdRoadRecord2(params);

					const {
						result1,
						result2
					} = data;
					state.congestIndex = result2.reverse().find(item => item.avgIndex > 0)?.avgIndex;
					drawRoad();
				}

				// 判断为交通运行界面
				if (props.is_ctdd_show) {
					emit('tags-click', currentRow);
				} else {
					// state.tableData = []
					emit('tableSelect', currentRow, state.sameDay, 'road');
				}
			};
			// 响应change事件
			const changeTable = () => {
				if (state.currentRow && JSON.stringify(state.currentRow) !== '{}') {
					emit('tableSelect', state.currentRow, state.sameDay, 'road');
				}
			};
			// 获取道路列表
			const getList = async () => {
				if (state.tableLoading) {
					return;
				}
				state.currentRow = '';
				state.tableLoading = true;
				let params = {
					roadName: state.sameDay.keywork,
					queryType: 'list', // 查询类型， 新增参数， list表示查询“重点道路”数据， edit表示查询“道路配置”的数据
				};
				// console.log("params",params);
				// return
				const data = await getCustomRoadSelectList(params);
				state.tableData = data;
				state.frontTableData = data;
				state.tableData = state.tableData?.slice(0, state.pageSize);
				state.tableLoading = false;
			};
			// 绘制道路
			const drawRoad = () => {
				state.polylineList.forEach((item) => {
					state.map.removeOverlay(item);
				});

				if (state.startPoint && state.endPoint) {
					state.polylineList = [];
					var driving = new window.BMap.RidingRoute(state.map, {
						renderOptions: {
							map: state.map,
							autoViewport: false
						},
						onSearchComplete(results) {
							// 绘制途径路线
							console.log('23432c');
							if (results) {
								var sy = new window.BMap.Symbol(
									BMap_Symbol_SHAPE_BACKWARD_OPEN_ARROW, {
										scale: 0.5, //图标缩放大小
										strokeColor: '#fff', //设置矢量图标的线填充颜色
										strokeWeight: '2', //设置线宽
									});
								var icons = new window.BMap.IconSequence(sy, '10', '30');
								var pts = results.getPlan(0).getRoute(0).getPath();
								console.log(state.congestIndex, '指数')
								let strokeColor = '#93D2F3'; // 默认颜色为蓝色（拥堵颜色）

								if (state.congestIndex < 1.5) {
									strokeColor = 'rgba(117, 197, 31, 1)'; // 小于 1.5 时为绿色
								} else if (state.congestIndex >= 1.5 && state
									.congestIndex <= 2) {
									strokeColor = 'rgba(248, 162, 46, 1)'; // 1.5 到 2 之间为黄色
								} else if (state.congestIndex > 2 && state
									.congestIndex <= 4) {
									strokeColor = 'rgba(244, 59, 29, 1)'; // 大于 2 时为红色
								} else {
									strokeColor = 'rgba(170, 32, 23, 1)'; // 大于 4 时为深红色
								}

								var polyline = new window.BMap.Polyline(pts, {
									icons: [icons],
									strokeWeight: '8',
									strokeOpacity: 0.5,
									strokeColor: strokeColor, // 使用动态的颜色
								});
								// var polyline = new window.BMap.Polyline(pts, {
								// 	icons: [icons],
								// 	strokeWeight: '8',
								// 	strokeOpacity: 0.5,
								// 	strokeColor: '#93D2F3',
								// });
								// polyline.setStrokeColor('#59FF59');
								// polyline.setStrokeOpacity(1);
								state.polylineList.push(polyline);
								state.map.addOverlay(polyline);
							}
						},
						onMarkersSet(routes) {
							// console.log('---', routes);
							routes.forEach((item, index) => {
								state.map.removeOverlay(item);
							});
						},
						onInfoHtmlSet() {},
						onPolylinesSet(routes) {
							console.log("routesroutes", routes);
							// 路线绘制
							routes.forEach((Route) => {
								var polyline = Route.getPolyline();
								polyline.setStrokeColor('#CB2D56');
								// polyline.setStrokeOpacity(1)
								polyline.setStrokeWeight(1);
							});
						},
					});

					//途经点方式化路线:
					// driving.search(state.startPoint, state.endPoint, { waypoints: state.viaPoint });

					//分段画路线:
					if (state.viaPoint && state.viaPoint.length) {
						for (let i = 0; i < state.viaPoint.length; i++) {
							if (i === 0) {
								driving.search(state.startPoint, state.viaPoint[i]);
							} else {
								driving.search(state.viaPoint[i - 1], state.viaPoint[i]);
							}
						}
						driving.search(state.viaPoint[state.viaPoint.length - 1], state.endPoint);
					} else {
						driving.search(state.startPoint, state.endPoint);
					}
				}
			};
			const changePage = (val) => {
				state.pageNum = val;
				let pre = val == 1 ? 0 : (state.pageNum - 1) * state.pageSize;
				console.log('state?.frontTableData', state?.frontTableData);
				state.tableData = state.frontTableData?.slice(pre, val * state.pageSize);
				// queryLogListFunc();
			};
			onMounted(() => {
				getList();
			});
			// 页面离开
			onBeforeUnmount(() => {
				clearTimeout(state.timer);
			});
			return {
				...toRefs(state),
				granularityClick,
				realRefresh,
				disabledWeek,
				currentChange,
				changeTable,
				changePage,
				Search,
				getList,
			};
		},
	});
</script>
<style scoped lang="less">
	.switch-group {
		//   margin: 1.5625vw 0;
		display: flex;
		align-items: center;

		.switch-item {
			flex-grow: 1;
			text-align: center;
			position: relative;
			color: rgba(255, 255, 255, 0.3);
			padding: 1.125vw;
			cursor: pointer;
		}

		.switch-item.active {
			color: white;
		}

		.switch-item.active::after {
			position: absolute;
			content: '';
			width: 30px;
			height: 4px;
			background: #037bff;
			border-radius: 2px;
			bottom: 0.5vw;
			left: 50%;
			margin-left: -15px;
		}

		.switch-line {
			width: 1px;
			height: 18px;
			background: #ffffff;
			opacity: 0.3;
		}
	}

	.tag-group {
		display: flex;
		color: rgba(255, 255, 255, 0.7);
		align-items: center;
		margin: 0 0 1vw;

		.tag-label {
			padding-right: 2.08vw;
			flex-grow: 0;
		}

		.tag-cell {
			display: flex;
			flex: 1;
		}

		.tag-item {
			padding: 4px 10px;
			cursor: pointer;
			margin-right: 1.0416vw;
		}

		.tag-item.active {
			color: white;
			background: #037bff;
			border-radius: 4px;
		}

		.today {
			display: flex;
			justify-content: space-between;
			flex-grow: 1;

			.refresh {
				cursor: pointer;
				color: #4979ff;
			}
		}

		.date {
			border: 1px solid rgba(3, 123, 255, 1);
			border-radius: 4px;
			flex: 1;
		}
	}

	.search {
		display: flex;
		justify-content: space-between;
		align-items: center;

		.search-input {
			border: 1px solid #037bff;
			border-radius: 8px;
			flex-grow: 3;
		}

		.export {
			flex-grow: 2;
			color: rgba(3, 123, 255, 1);
			display: flex;
			text-align: right;
			align-items: center;
			justify-content: flex-end;

			span {
				cursor: pointer;
			}
		}
	}

	.table {
		margin: 1.5625vw 0;
		width: 100%;

		:deep(.el-table) {
			thead tr {
				background: linear-gradient(-90deg, #037bff 0%, #3996fc 100%) !important;
				box-shadow: 0px 4px 0px 0px rgba(77, 150, 236, 0.4);
				border-radius: 8px 0px 8px 0px;
			}

			.el-table__inner-wrapper::before {
				display: none;
			}

			.el-table__cell {
				padding: 15px 0;
			}

			.el-table__body tr.current-row {
				border: 1px solid #047cff !important;
				border-radius: 8px;
			}

			.el-table__body tr.current-row>td.el-table__cell {
				background: rgba(77, 150, 236, 0.4);
			}
		}

		:deep(.el-table__body) {
			.index-color {
				width: 20px;
				height: 20px;
				line-height: 20px;
				text-align: center;
				border-radius: 50%;
			}

			.congestion-num {
				color: rgba(117, 197, 31, 1);
			}

			.congestion-num.orange {
				color: rgba(248, 162, 46, 1);
			}

			.congestion-num.red {
				color: rgba(244, 59, 29, 1);
			}

			& tr:nth-child(1) {
				& td:first-child {
					.index-color {
						background: #fb6036;
						color: white;
					}
				}
			}

			& tr:nth-child(2) {
				& td:first-child {
					.index-color {
						background: rgba(151, 203, 243, 1);
						color: white;
					}
				}
			}

			& tr:nth-child(3) {
				& td:first-child {
					.index-color {
						background: rgba(177, 102, 53, 1);
						color: white;
					}
				}
			}
		}
	}

	.pagination-sty {
		position: fixed;
		bottom: 15px;
	}
</style>
<style lang="less" scoped>
	.el-popper.is-light {
		background-color: rgba(5, 12, 23) !important;
		border: 1px solid #3d618a54 !important;
	}

	.not-data {
		padding-top: 1vw;
		color: white;
	}
</style>